//
//  LoginViewController.m
//  GYMWinners
//
//  Created by Logic Solutions on 4/7/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "LoginViewController.h"
#import "SignViewController.h"
#import "SpaceViewController.h"
#import "NearbyViewController.h"
#import "TopboardViewController.h"

#import "ASIHTTPRequest.h"
#import "ASIFormDataRequest.h"
#import "SBJSON.h"
#import "MBProgressHUD.h"
#import "BaseroutAPI.h"
#import "AppDelegate.h"

@interface LoginViewController ()

@end

@implementation LoginViewController
@synthesize tabBarController;
@synthesize spaceNavController;
@synthesize signNavController;
@synthesize nearbyNavController;
@synthesize topNavController;
@synthesize emailText;
@synthesize passwordText;

-(IBAction)backgroundTouched:(id)sender{
    [emailText resignFirstResponder];
    [passwordText resignFirstResponder];
}

-(IBAction)textfieldReturn:(id)sender{
    [sender resignFirstResponder];
}


- (BOOL) validate
{
    if( [emailText.text length] < 1)
    {
        [[BaseroutAPI sharedInstance] MessageBox:@"输入错误" Message:@"请输入用户名或邮件地址"];
        
        return NO;
    }
    
    if( [passwordText.text length] < 1 )
    {
        [[BaseroutAPI sharedInstance] MessageBox:@"密码错误" Message:@"请输入密码"];
        
        return NO;
    }
    
    return YES;
    
}

-(IBAction)finishLogin{
    
    [emailText resignFirstResponder];
    [passwordText resignFirstResponder];
    
    if([self validate] == NO)
        return;
    
    NSMutableDictionary *slist = [[NSMutableDictionary alloc] init];
    [slist setObject:emailText.text forKey:@"usernameOrEmail"];
    [slist setObject:passwordText.text forKey:@"password"];
    [self zSendServer:slist theTitle:@"请稍等" theCommand:@"/login"];

}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
}

- (void)viewDidUnload
{
    [self setEmailText:nil];
    [self setPasswordText:nil];
    [super viewDidUnload];
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - ASIFormDataRequest delegate

- (void)requestFinished:(ASIHTTPRequest *)request
{    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    
    if (request.responseStatusCode == 200) {
        
        NSString *responseString = [request responseString];
        NSLog(@"responseString=[%@]", responseString);   
        NSDictionary *responseDict = [responseString JSONValue];
        NSString *customerID = [NSString stringWithFormat:@"%@", [responseDict objectForKey:@"id"]];
        NSString *status = [responseDict objectForKey:@"status"];
        
        if( [[BaseroutAPI sharedInstance] validateString:customerID] )
        {
            // Login OK!
            [[BaseroutAPI sharedInstance] zSetVar:@"customerid" theValue:[responseDict objectForKey:@"id"]];
            [[BaseroutAPI sharedInstance] zSetVar:@"password" theValue:[responseDict objectForKey:@"password"]];
            [[BaseroutAPI sharedInstance] zSetVar:@"username" theValue:[responseDict objectForKey:@"username"]];
            [[BaseroutAPI sharedInstance] zSetVar:@"email" theValue:[responseDict objectForKey:@"email"]];
            
            [[BaseroutAPI sharedInstance] zSetVar:@"loginStatus" theValue:[responseDict objectForKey:@"YES"]];
            
            spaceNavController=[[UINavigationController alloc] init];
            signNavController=[[UINavigationController alloc] init];
            nearbyNavController=[[UINavigationController alloc] init];
            topNavController=[[UINavigationController alloc] init];
            
            
            SpaceViewController* spaceViewController=[[SpaceViewController alloc] init];
            [spaceNavController pushViewController:spaceViewController animated:NO];
            spaceNavController.tabBarItem=[[UITabBarItem alloc] initWithTitle:@"空间" image:nil tag:0];
            
            SignViewController* signViewController=[[SignViewController alloc] init];
            [signNavController pushViewController:signViewController animated:NO];
            signNavController.tabBarItem=[[UITabBarItem alloc] initWithTitle:@"签到" image:nil tag:0];
            
            
            NearbyViewController* nearbyViewController=[[NearbyViewController alloc] init];
            [nearbyNavController pushViewController:nearbyViewController animated:NO];
            nearbyNavController.tabBarItem=[[UITabBarItem alloc] initWithTitle:@"周边" image:nil tag:0];
            
            TopboardViewController* topboardViewController=[[TopboardViewController alloc] init];
            [topNavController pushViewController:topboardViewController animated:NO];
            topNavController.tabBarItem=[[UITabBarItem alloc] initWithTitle:@"排行" image:nil tag:0];
            
            tabBarController=[[UITabBarController alloc] init];
            tabBarController.viewControllers=[NSArray arrayWithObjects:spaceNavController,signNavController,nearbyNavController,topNavController, nil];
            
            //Clean the text so after logout you will not see previous login info
            emailText.text = @"";
            passwordText.text = @"";
            
            AppDelegate *appdel = [[UIApplication sharedApplication] delegate];
            appdel.tabBarController = tabBarController;
            
        
            [UIView beginAnimations:nil context:NULL];
            [UIView setAnimationDuration:0.8];
            [UIView setAnimationTransition:UIViewAnimationTransitionNone forView:self.view.window cache:NO];
            
            [self.view.window addSubview:tabBarController.view];
            
            [UIView commitAnimations];
            
            [self.navigationController popToRootViewControllerAnimated:NO];
        }
        else
        {
            [[BaseroutAPI sharedInstance] MessageBox:@"提示" Message:@"登录失败"]; 
        }
        
    } else {
        NSLog(@"Unexpected error");  
        [[BaseroutAPI sharedInstance] MessageBox:@"提示" Message:@"通讯失败"];
    }
    
}

- (void)requestFailed:(ASIHTTPRequest *)request
{    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    
    NSError *error = [request error];
    NSLog(@"Error=%@", error.localizedDescription);   
    
    [[BaseroutAPI sharedInstance] MessageBox:@"提示" Message:@"通讯失败"];
}

@end
